from pydantic import BaseModel, Field, field_validator
from typing import Optional
from datetime import datetime
from ..core.utils import generate_orderid

class CEQRequest(BaseModel):
    """CEQ 余额查询请求"""
    appid: str = Field(..., max_length=3, description="交易来源")
    pan: str = Field(..., max_length=19, description="卡号")
    orderid: Optional[str] = Field(None, max_length=30, description="订单流水号")

    @field_validator('appid')
    def validate_appid(cls, v):
        valid_appids = {'01', '02', '03', '04', '05'}
        if v not in valid_appids:
            raise ValueError(f"appid必须是以下值之一: {', '.join(valid_appids)}")
        return v

    @field_validator('orderid')
    def validate_orderid(cls, v):
        if v is None:
            return generate_orderid("01")  # 如果未提供，生成新的订单号
        if len(v) < 8:
            raise ValueError("订单号长度不能小于8位")
        # 检查订单号格式：前两位是appid，接着是日期时间
        try:
            date_part = v[2:14]  # 获取日期时间部分
            datetime.strptime(date_part, '%Y%m%d%H%M')
        except ValueError:
            raise ValueError("订单号格式错误：前两位是appid，后面必须包含日期时间(YYYYMMDDHHmm)")
        return v

    class Config:
        json_schema_extra = {
            "example": {
                "appid": "01",
                "pan": "2168890010126843",
                "orderid": "01202507101423123456"
            }
        }

class CEQResponse(BaseModel):
    """CEQ 余额查询响应"""
    resp_code: str = Field(max_length=5, description="响应码")
    balance: str = Field(min_length=12, description="账户余额")
    card_stat: str = Field(max_length=2, description="卡片状态")
    trans_sn: str = Field(max_length=30, description="卡系统流水号")
    error_msg: Optional[str] = Field(None, description="错误信息") 